using LiteDB;
using PHMEE.VibrationDataGenerator.Data;

namespace PHMEE.VibrationDataGenerator.Services;

public class TaskManagementService
{
    private readonly TaskConfigRepository _taskConfigRepository;
    private readonly TaskManager _taskManager;

    public TaskManagementService(TaskConfigRepository taskConfigRepository, TaskManager taskManager)
    {
        _taskConfigRepository = taskConfigRepository;
        _taskManager = taskManager;
    }
    
    public async Task AddTaskAsync(TaskConfig taskConfig)
    {
        // 保存到数据库
        _taskConfigRepository.AddTask(taskConfig);
        
        // 调度任务
        await _taskManager.AddTask(taskConfig);
    }
    
    public async Task UpdateTaskAsync(TaskConfig taskConfig)
    {
        // 更新数据库
        _taskConfigRepository.UpdateTask(taskConfig);
        
        var oldTaskConfig = _taskConfigRepository.GetTaskById(taskConfig.Id);
        
        // 调度任务
        await _taskManager.UpdateTask(taskConfig, oldTaskConfig);
    }
    
    public async Task DeleteTaskAsync(ObjectId taskId)
    {
        // 从数据库中删除
        _taskConfigRepository.DeleteTask(taskId);
        
        // 删除任务
        await _taskManager.DeleteTask(taskId);
    }
    
    public async Task ToggleStatusAsync(ObjectId taskId)
    {
        // 获取任务配置
        var taskConfig = _taskConfigRepository.GetTaskById(taskId);
        
        // deep clone taskConfig
        var oldTaskConfig = System.Text.Json.JsonSerializer.Deserialize<TaskConfig>(System.Text.Json.JsonSerializer.Serialize(taskConfig));
        if (oldTaskConfig == null)
        {
            throw new Exception("Failed to deep clone taskConfig");
        }
        
        // 切换任务状态
        taskConfig.Status = taskConfig.Status == VibDataGenerateTaskStatus.Running
            ? VibDataGenerateTaskStatus.Stopped
            : VibDataGenerateTaskStatus.Running;
        
        // 更新数据库
        _taskConfigRepository.UpdateTask(taskConfig);
        
        // 调度任务
        await _taskManager.UpdateTask(taskConfig, oldTaskConfig);
    }
}